package com.indi.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.indi.common.constant.AuthConstant;
import com.indi.common.to.MemberTO;
import com.indi.common.utils.HttpUtils;
import com.indi.common.utils.R;
import com.indi.gulimall.auth.feign.MemberFeignService;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/web/oauth2")
public class OAuth2Controller {
    @Resource
    private MemberFeignService memberFeignService;

    @GetMapping("/gitee/success")
    @ApiOperation("Gitee登录回调")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        // 准备请求参数
        Map<String, String> params = new HashMap<>();
        params.put("client_id", "c1b38052f6920a73ac1cc16952f594e9cdb35e8e9923387fe3e1eea26dbb1077");
        params.put("redirect_uri", "http://auth.gulimall.com/web/oauth2/gitee/success");
        params.put("client_secret", "e7c59943fb0dbce038c560de7dc8545041208c00fc18a4e529d2a413ec310616");
        params.put("code", code);
        params.put("grant_type", "authorization_code");

        // 获取accesstoken
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", null, null, params);

        if (response.getStatusLine().getStatusCode() == 200) {
            // 说明获取到了
            // 取出返回数据
            String giteeInfo = EntityUtils.toString(response.getEntity());
            R r = memberFeignService.giteeLogin(giteeInfo);
            if (r.getCode() == 0) {
                // 将登录的用户信息放到 session 中
                MemberTO memberTO = r.getData("data", new TypeReference<MemberTO>() {
                });
                session.setAttribute(AuthConstant.SESSION_ATTR_NAME, memberTO);
                return "redirect:http://gulimall.com/";
            }

        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }

        return "redirect:http://auth.gulimall.com/login.html";
    }
}
